// 引入Electron的ipcRenderer
const { ipcRenderer } = require('electron');

// 应用状态
class AppState {
    constructor() {
        this.localPath = '';
        this.remotePath = '/';
        this.selectedProvider = null;
        this.compareResult = null;
        this.isUploading = false;
        this.isComparing = false;
        this.uploadCompleted = false;
        this.uploadProgress = null;
        this.isConnected = false;
        this.connectionChecking = false;
    }
}

const appState = new AppState();

// DOM元素引用
const elements = {
    localPath: document.getElementById('localPath'),
    selectLocalBtn: document.getElementById('selectLocalBtn'),
    remotePath: document.getElementById('remotePath'),
    providerCards: document.querySelectorAll('.provider-card'),
    compareBtn: document.getElementById('compareBtn'),
    uploadBtn: document.getElementById('uploadBtn'),
    comparePanel: document.getElementById('comparePanel'),
    uploadPanel: document.getElementById('uploadPanel'),
    configModal: document.getElementById('configModal'),
    modalClose: document.getElementById('modalClose'),
    configForm: document.getElementById('configForm'),
    saveConfigBtn: document.getElementById('saveConfigBtn'),
    testConnectionBtn: document.getElementById('testConnectionBtn'),
    modalTitle: document.getElementById('modalTitle'),
    messageContainer: document.getElementById('messageContainer'),
    // 设置相关元素
    settingsBtn: document.getElementById('settingsBtn'),
    settingsModal: document.getElementById('settingsModal'),
    settingsModalClose: document.getElementById('settingsModalClose'),
    accountConfigModal: document.getElementById('accountConfigModal'),
    accountConfigModalClose: document.getElementById('accountConfigModalClose'),
    accountConfigForm: document.getElementById('accountConfigForm'),
    saveAccountBtn: document.getElementById('saveAccountBtn'),
    // 账号选择相关元素
    accountSelect: document.getElementById('accountSelect'),
    addAccountBtn: document.getElementById('addAccountBtn'),
    // 新的云服务选择器元素
    providerSelect: document.getElementById('providerSelect'),
    mainAccountSelect: document.getElementById('mainAccountSelect'),
    accountSelectGroup: document.getElementById('accountSelectGroup'),
    manageAccountsBtn: document.getElementById('manageAccountsBtn'),
    connectionStatus: document.getElementById('connectionStatus'),
    statusText: document.getElementById('statusText')
};

// 初始化应用
async function initializeApp() {
    setupEventListeners();
    await loadLastLocalPath();
    await loadLastRemotePath();
    await initializeMainCloudSelector();
    updateUI();
}

// 设置事件监听器
function setupEventListeners() {
    // 选择本地目录
    elements.selectLocalBtn.addEventListener('click', selectLocalDirectory);
    
    // 远程路径输入
    elements.remotePath.addEventListener('input', (e) => {
        appState.remotePath = e.target.value || '/';
        updateUI();
    });
    
    // 远程路径输入完成时保存历史记录
    elements.remotePath.addEventListener('blur', async (e) => {
        const remotePath = e.target.value.trim();
        if (remotePath && remotePath !== '/') {
            await ipcRenderer.invoke('save-remote-path-history', remotePath);
        }
    });
    
    // 回车键保存历史记录
    elements.remotePath.addEventListener('keypress', async (e) => {
        if (e.key === 'Enter') {
            const remotePath = e.target.value.trim();
            if (remotePath && remotePath !== '/') {
                await ipcRenderer.invoke('save-remote-path-history', remotePath);
            }
        }
    });
    
    // 云服务提供商选择
    if (elements.providerSelect) {
        elements.providerSelect.addEventListener('change', onProviderSelectChange);
    }
    
    // 菜单事件监听器
    setupMenuEventListeners();
    
    // 主界面账号选择
    if (elements.mainAccountSelect) {
        elements.mainAccountSelect.addEventListener('change', onMainAccountSelectChange);
    }
    
    // 管理账号按钮
    if (elements.manageAccountsBtn) {
        elements.manageAccountsBtn.addEventListener('click', openSettingsModal);
    }
    
    // 比较文件按钮
    elements.compareBtn.addEventListener('click', compareFiles);
    
    // 上传按钮
    elements.uploadBtn.addEventListener('click', startUpload);
    
    // 模态框关闭
    elements.modalClose.addEventListener('click', closeModal);
    elements.configModal.addEventListener('click', (e) => {
        if (e.target === elements.configModal) {
            closeModal();
        }
    });
    
    // 保存配置
    elements.saveConfigBtn.addEventListener('click', saveConfig);
    
    // 测试连接
    elements.testConnectionBtn.addEventListener('click', testConnection);
    
    // 监听上传进度
    ipcRenderer.on('upload-progress', (event, progress) => {
        updateUploadProgress(progress);
    });
    
    // 设置按钮
    if (elements.settingsBtn) {
        elements.settingsBtn.addEventListener('click', openSettingsModal);
    }
    
    // 设置模态框关闭
    if (elements.settingsModalClose) {
        elements.settingsModalClose.addEventListener('click', closeSettingsModal);
    }
    if (elements.settingsModal) {
        elements.settingsModal.addEventListener('click', (e) => {
            if (e.target === elements.settingsModal) {
                closeSettingsModal();
            }
        });
    }
    
    // 账号配置模态框关闭
    if (elements.accountConfigModalClose) {
        elements.accountConfigModalClose.addEventListener('click', closeAccountConfigModal);
    }
    if (elements.accountConfigModal) {
        elements.accountConfigModal.addEventListener('click', (e) => {
            if (e.target === elements.accountConfigModal) {
                closeAccountConfigModal();
            }
        });
    }
    
    // 保存账号配置
    if (elements.saveAccountBtn) {
        elements.saveAccountBtn.addEventListener('click', saveAccountConfig);
    }
    
    // 添加新账号按钮（设置界面顶部的按钮）
    if (elements.addAccountBtn) {
        elements.addAccountBtn.addEventListener('click', () => {
            openAccountConfigModal();
        });
    }
    
    // 配置模态框中的添加新账号按钮
    const addNewAccountBtn = document.getElementById('addNewAccountBtn');
    if (addNewAccountBtn) {
        addNewAccountBtn.addEventListener('click', () => {
            closeModal();
            openAccountConfigModal(null, appState.selectedProvider);
        });
    }
    
    // 测试账号连接按钮
    const testAccountConnectionBtn = document.getElementById('testAccountConnectionBtn');
    if (testAccountConnectionBtn) {
        testAccountConnectionBtn.addEventListener('click', testAccountConnection);
    }
    
    // 设置标签页切换
    const tabBtns = document.querySelectorAll('.tab-btn');
    tabBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            const tabName = btn.dataset.tab;
            switchTab(tabName);
        });
    });
    
    // 账号选择变化
    if (elements.accountSelect) {
        elements.accountSelect.addEventListener('change', onAccountSelectChange);
    }
}

// 选择本地目录
async function selectLocalDirectory() {
    try {
        const result = await ipcRenderer.invoke('select-local-directory');
        if (result) {
            appState.localPath = result;
            elements.localPath.value = result;
            // 保存到历史记录
            await ipcRenderer.invoke('save-local-path-history', result);
            updateUI();
            showMessage('本地目录选择成功', 'success');
        }
    } catch (error) {
        console.error('选择目录失败:', error);
        showMessage('选择目录失败: ' + error.message, 'error');
    }
}

// 选择云服务提供商
function selectProvider(provider) {
    // 移除之前的选中状态
    elements.providerCards.forEach(card => {
        card.classList.remove('selected');
    });
    
    // 添加选中状态
    const selectedCard = document.querySelector(`[data-provider="${provider}"]`);
    selectedCard.classList.add('selected');
    
    appState.selectedProvider = provider;
    
    // 自动检查连接状态
    checkConnectionStatus(provider);
    
    updateUI();
    
    // 打开配置模态框
    openConfigModal(provider);
}

// 打开配置模态框
async function openConfigModal(provider) {
    const providerNames = {
        tencent: '腾讯云 COS',
        aliyun: '阿里云 OSS',
        bytedance: '字节云 TOS',
        aws: 'AWS S3',
        huawei: '华为云 OBS'
    };
    
    elements.modalTitle.textContent = `${providerNames[provider]} 配置`;
    
    // 加载账号列表
    await loadAccountsForProvider(provider);
    
    // 清空表单，等待用户选择账号
    elements.configForm.reset();
    
    elements.configModal.style.display = 'block';
}

// 关闭模态框
function closeModal() {
    elements.configModal.style.display = 'none';
}

// 保存配置
async function saveConfig() {
    const formData = new FormData(elements.configForm);
    const config = {
        provider: appState.selectedProvider,
        accessKeyId: document.getElementById('accessKeyId').value,
        secretAccessKey: document.getElementById('secretAccessKey').value,
        region: document.getElementById('region').value,
        bucket: document.getElementById('bucket').value,
        endpoint: document.getElementById('endpoint').value
    };
    
    // 验证必填字段
    if (!config.accessKeyId || !config.secretAccessKey || !config.region || !config.bucket) {
        showMessage('请填写所有必填字段', 'error');
        return;
    }
    
    try {
        const success = await ipcRenderer.invoke('save-cloud-config', config);
        if (success) {
            showMessage('配置保存成功', 'success');
            closeModal();
            loadProviderConfigs();
            
            // 如果保存的是当前选中的云服务配置，自动检查连接状态
            if (appState.selectedProvider === config.provider) {
                checkConnectionStatus(config.provider);
            }
        } else {
            showMessage('配置保存失败', 'error');
        }
    } catch (error) {
        console.error('保存配置失败:', error);
        showMessage('保存配置失败: ' + error.message, 'error');
    }
}

// 自动检查连接状态
async function checkConnectionStatus(provider) {
    if (appState.connectionChecking) return;
    
    try {
        appState.connectionChecking = true;
        appState.isConnected = false;
        updateUI();
        
        // 获取保存的配置
        const config = await ipcRenderer.invoke('get-cloud-config', provider);
        
        if (!config || !config.accessKeyId || !config.secretAccessKey || !config.region || !config.bucket) {
            appState.isConnected = false;
            showMessage('云服务配置不完整，请完善配置信息', 'warning');
            return;
        }
        
        // 调用后端测试连接
        const result = await ipcRenderer.invoke('test-cloud-connection', config);
        
        if (result.success) {
            appState.isConnected = true;
            showMessage('云服务连接正常', 'success');
        } else {
            appState.isConnected = false;
            showMessage(`云服务连接失败: ${result.error}`, 'error');
        }
    } catch (error) {
        console.error('检查连接状态失败:', error);
        appState.isConnected = false;
        showMessage('检查连接状态失败: ' + error.message, 'error');
    } finally {
        appState.connectionChecking = false;
        updateUI();
    }
}

// 测试连接
async function testConnection() {
    const config = {
        provider: appState.selectedProvider,
        accessKeyId: document.getElementById('accessKeyId').value,
        secretAccessKey: document.getElementById('secretAccessKey').value,
        region: document.getElementById('region').value,
        bucket: document.getElementById('bucket').value,
        endpoint: document.getElementById('endpoint').value
    };
    
    if (!config.accessKeyId || !config.secretAccessKey || !config.region || !config.bucket) {
        showMessage('请填写所有必填字段', 'error');
        return;
    }
    
    try {
        elements.testConnectionBtn.disabled = true;
        elements.testConnectionBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 测试中...';
        
        // 调用后端测试连接
        const result = await ipcRenderer.invoke('test-cloud-connection', config);
        
        if (result.success) {
            showMessage('连接测试成功', 'success');
        } else {
            showMessage(`连接测试失败: ${result.error}`, 'error');
        }
    } catch (error) {
        console.error('连接测试失败:', error);
        showMessage('连接测试失败: ' + error.message, 'error');
    } finally {
        elements.testConnectionBtn.disabled = false;
        elements.testConnectionBtn.innerHTML = '<i class="fas fa-plug"></i> 测试连接';
    }
}

// 加载最后一次使用的远程目录
async function loadLastRemotePath() {
    try {
        const lastRemotePath = await ipcRenderer.invoke('get-last-remote-path');
        if (lastRemotePath) {
            appState.remotePath = lastRemotePath;
            elements.remotePath.value = lastRemotePath;
        }
    } catch (error) {
        console.error('加载最后使用的远程目录失败:', error);
    }
}

// 加载最后使用的本地目录
async function loadLastLocalPath() {
    try {
        const lastLocalPath = await ipcRenderer.invoke('get-last-local-path');
        if (lastLocalPath) {
            appState.localPath = lastLocalPath;
            elements.localPath.value = lastLocalPath;
        }
    } catch (error) {
        console.error('加载最后使用的本地目录失败:', error);
    }
}

// 加载云服务提供商配置状态
async function loadProviderConfigs() {
    const providers = ['tencent', 'aliyun', 'bytedance', 'aws', 'huawei'];
    
    for (const provider of providers) {
        try {
            const accounts = await ipcRenderer.invoke('get-provider-accounts', provider);
            const statusElement = document.getElementById(`${provider}Status`);
            
            if (accounts && accounts.length > 0) {
                // 查找默认账号
                const defaultAccount = accounts.find(account => account.isDefault);
                const displayAccount = defaultAccount || accounts[0];
                
                statusElement.innerHTML = `<i class="fas fa-circle"></i> ${displayAccount.accountName}`;
                statusElement.classList.add('configured');
            } else {
                statusElement.innerHTML = '<i class="fas fa-circle"></i> 未配置';
                statusElement.classList.remove('configured');
            }
        } catch (error) {
            console.error(`加载${provider}配置失败:`, error);
            const statusElement = document.getElementById(`${provider}Status`);
            statusElement.innerHTML = '<i class="fas fa-circle"></i> 未配置';
            statusElement.classList.remove('configured');
        }
    }
}

// 比较文件
async function compareFiles() {
    if (!appState.localPath || !appState.selectedProvider) {
        showMessage('请先选择本地目录和云服务提供商', 'error');
        return;
    }
    
    try {
        appState.isComparing = true;
        appState.compareResult = null;
        appState.uploadCompleted = false;
        updateUI();
        
        elements.compareBtn.disabled = true;
        elements.compareBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 比较中...';
        
        const result = await ipcRenderer.invoke('compare-files', 
            appState.localPath, 
            appState.remotePath, 
            appState.selectedProvider
        );
        
        appState.compareResult = result;
        displayCompareResult(result);
        
        showMessage('文件比较完成', 'success');
    } catch (error) {
        console.error('文件比较失败:', error);
        showMessage('文件比较失败: ' + error.message, 'error');
    } finally {
        appState.isComparing = false;
        elements.compareBtn.disabled = false;
        elements.compareBtn.innerHTML = '<i class="fas fa-search"></i> 比较文件';
        updateUI();
    }
}

// 显示比较结果
function displayCompareResult(result) {
    // 更新统计信息
    document.getElementById('newFilesCount').textContent = result.newFiles.length;
    document.getElementById('modifiedFilesCount').textContent = result.modifiedFiles.length;
    document.getElementById('unchangedFilesCount').textContent = result.unchangedFiles.length;
    document.getElementById('totalSize').textContent = formatFileSize(result.totalSize);
    
    // 显示文件列表 - 只显示新增和修改的文件
    const fileList = document.getElementById('fileList');
    fileList.innerHTML = '';
    
    // 只包含需要上传的文件（新增和修改的）
    const filesToUpload = [
        ...result.newFiles.map(f => ({ ...f, status: 'new' })),
        ...result.modifiedFiles.map(f => ({ ...f, status: 'modified' }))
    ];
    
    if (filesToUpload.length === 0) {
        const noFilesMessage = document.createElement('div');
        noFilesMessage.className = 'no-files-message';
        noFilesMessage.innerHTML = `
            <div class="no-files-content">
                <i class="fas fa-check-circle"></i>
                <p>所有文件都是最新的，无需上传</p>
            </div>
        `;
        fileList.appendChild(noFilesMessage);
    } else {
        // 添加分组标题
        if (result.newFiles.length > 0) {
            const newFilesHeader = document.createElement('div');
            newFilesHeader.className = 'file-group-header new';
            newFilesHeader.innerHTML = `
                <i class="fas fa-plus-circle"></i>
                <span>新增文件 (${result.newFiles.length})</span>
            `;
            fileList.appendChild(newFilesHeader);
            
            result.newFiles.forEach(file => {
                const fileItem = document.createElement('div');
                fileItem.className = 'file-item new';
                fileItem.innerHTML = `
                    <div class="file-name">${file.relativePath}</div>
                    <div class="file-size">${formatFileSize(file.size)}</div>
                `;
                fileList.appendChild(fileItem);
            });
        }
        
        if (result.modifiedFiles.length > 0) {
            const modifiedFilesHeader = document.createElement('div');
            modifiedFilesHeader.className = 'file-group-header modified';
            modifiedFilesHeader.innerHTML = `
                <i class="fas fa-edit"></i>
                <span>修改文件 (${result.modifiedFiles.length})</span>
            `;
            fileList.appendChild(modifiedFilesHeader);
            
            result.modifiedFiles.forEach(file => {
                const fileItem = document.createElement('div');
                fileItem.className = 'file-item modified';
                fileItem.innerHTML = `
                    <div class="file-name">${file.relativePath}</div>
                    <div class="file-size">${formatFileSize(file.size)}</div>
                `;
                fileList.appendChild(fileItem);
            });
        }
    }
    
    elements.comparePanel.style.display = 'block';
}

// 开始上传
async function startUpload() {
    if (!appState.compareResult || !appState.selectedProvider) {
        showMessage('请先进行文件比较', 'error');
        return;
    }
    
    const filesToUpload = [
        ...appState.compareResult.newFiles,
        ...appState.compareResult.modifiedFiles
    ];
    
    if (filesToUpload.length === 0) {
        showMessage('没有需要上传的文件', 'warning');
        return;
    }
    
    const uploadConfig = {
        provider: appState.selectedProvider,
        localPath: appState.localPath,
        remotePath: appState.remotePath,
        files: filesToUpload
    };
    
    try {
        appState.isUploading = true;
        appState.uploadCompleted = false;
        updateUI();
        
        elements.uploadPanel.style.display = 'block';
        
        const success = await ipcRenderer.invoke('start-upload', uploadConfig);
        
        if (success) {
            appState.uploadCompleted = true;
            showMessage('上传完成', 'success');
        } else {
            showMessage('上传失败', 'error');
        }
    } catch (error) {
        console.error('上传失败:', error);
        showMessage('上传失败: ' + error.message, 'error');
    } finally {
        appState.isUploading = false;
        updateUI();
    }
}

// 更新上传进度
function updateUploadProgress(progress) {
    appState.uploadProgress = progress;
    
    document.getElementById('currentFile').textContent = progress.currentFile || '准备上传...';
    document.getElementById('fileProgress').textContent = `${progress.currentFileIndex}/${progress.totalFiles}`;
    document.getElementById('sizeProgress').textContent = `${formatFileSize(progress.uploadedSize)} / ${formatFileSize(progress.totalSize)}`;
    document.getElementById('uploadSpeed').textContent = `${formatFileSize(progress.speed)}/s`;
    document.getElementById('progressFill').style.width = `${progress.totalProgress}%`;
    document.getElementById('progressPercentage').textContent = `${Math.round(progress.totalProgress)}%`;
    
    // 更新成功和失败数量
    if (progress.successCount !== undefined) {
        document.getElementById('successCount').textContent = progress.successCount;
    }
    if (progress.failedCount !== undefined) {
        document.getElementById('failedCount').textContent = progress.failedCount;
    }
    
    // 更新重试信息
    const retryInfo = document.getElementById('retryInfo');
    if (progress.currentRetryAttempt > 0) {
        document.getElementById('retryCount').textContent = progress.retryCount || 0;
        document.getElementById('currentRetryAttempt').textContent = progress.currentRetryAttempt;
        retryInfo.style.display = 'inline';
    } else {
        retryInfo.style.display = 'none';
    }
    
    if (progress.status === 'completed') {
        const finalMessage = progress.failedCount > 0 
            ? `上传完成，成功: ${progress.successCount}，失败: ${progress.failedCount}`
            : '上传完成';
        showMessage(finalMessage, progress.failedCount > 0 ? 'warning' : 'success');
        appState.isUploading = false;
        appState.uploadCompleted = true;
        updateUI();
    } else if (progress.status === 'error') {
        showMessage(`上传错误: ${progress.error}`, 'error');
        appState.isUploading = false;
        updateUI();
    }
}

// 更新UI状态
function updateUI() {
    // 更新比较按钮状态 - 需要本地路径、选择的云服务商、云服务连接正常，且不在上传或比较中
    const canCompare = appState.localPath && 
                      appState.selectedProvider && 
                      appState.isConnected && 
                      !appState.isUploading && 
                      !appState.isComparing && 
                      !appState.connectionChecking;
    
    elements.compareBtn.disabled = !canCompare;
    
    // 更新比较按钮文本
    if (appState.connectionChecking) {
        elements.compareBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 检查连接中...';
    } else if (!appState.localPath) {
        elements.compareBtn.innerHTML = '<i class="fas fa-balance-scale"></i> 比较文件 (请选择本地目录)';
    } else if (!appState.selectedProvider) {
        elements.compareBtn.innerHTML = '<i class="fas fa-balance-scale"></i> 比较文件 (请选择云服务)';
    } else if (!appState.isConnected) {
        elements.compareBtn.innerHTML = '<i class="fas fa-balance-scale"></i> 比较文件 (云服务未连接)';
    } else if (appState.isComparing) {
        elements.compareBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 比较中...';
    } else {
        elements.compareBtn.innerHTML = '<i class="fas fa-balance-scale"></i> 比较文件';
    }
    
    // 更新上传按钮状态和文本
    if (appState.isComparing || !appState.compareResult) {
        // 状态1: 上传前，没有比较文件或比较中 - 不可点击
        elements.uploadBtn.disabled = true;
        elements.uploadBtn.innerHTML = '<i class="fas fa-upload"></i> 开始上传';
    } else if (appState.isUploading) {
        // 状态2: 上传中 - 不可点击，显示上传中
        elements.uploadBtn.disabled = true;
        elements.uploadBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 上传中...';
    } else if (appState.uploadCompleted) {
        // 状态3: 上传完成 - 不可点击，显示上传完成
        elements.uploadBtn.disabled = true;
        elements.uploadBtn.innerHTML = '<i class="fas fa-check"></i> 上传完成';
    } else {
        // 可以上传的状态
        elements.uploadBtn.disabled = false;
        elements.uploadBtn.innerHTML = '<i class="fas fa-upload"></i> 开始上传';
    }
}

// 显示消息
function showMessage(message, type = 'info') {
    const messageElement = document.createElement('div');
    messageElement.className = `message ${type}`;
    messageElement.textContent = message;
    
    elements.messageContainer.appendChild(messageElement);
    
    // 3秒后自动移除消息
    setTimeout(() => {
        if (messageElement.parentNode) {
            messageElement.parentNode.removeChild(messageElement);
        }
    }, 3000);
}

// 格式化文件大小
function formatFileSize(bytes) {
    if (bytes === 0) return '0 B';
    
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 页面加载完成后初始化应用
// 设置页面相关函数
function openSettingsModal() {
    if (elements.settingsModal) {
        elements.settingsModal.style.display = 'block';
        loadAccountsForSettings();
    }
}

function closeSettingsModal() {
    if (elements.settingsModal) {
        elements.settingsModal.style.display = 'none';
    }
}

function openAccountConfigModal(accountId = null, provider = null) {
    if (elements.accountConfigModal) {
        elements.accountConfigModal.style.display = 'block';
        
        // 如果是编辑现有账号
        if (accountId && provider) {
            loadAccountForEdit(accountId, provider);
        } else {
            // 新建账号，清空表单
            if (elements.accountConfigForm) {
                elements.accountConfigForm.reset();
                // 清除编辑状态
                delete elements.accountConfigForm.dataset.accountId;
            }
            
            // 重置模态框标题
            const titleElement = document.getElementById('accountConfigTitle');
            if (titleElement) {
                titleElement.textContent = '添加账号';
            }
            
            // 如果有选中的提供商，预设提供商
            if (provider) {
                const providerSelect = document.getElementById('accountProvider');
                if (providerSelect) {
                    providerSelect.value = provider;
                }
            }
        }
    }
}

function closeAccountConfigModal() {
    if (elements.accountConfigModal) {
        elements.accountConfigModal.style.display = 'none';
    }
}

async function loadAccountsForSettings() {
    try {
        const providers = ['tencent', 'aliyun', 'bytedance', 'aws', 'huawei'];
        
        for (const provider of providers) {
            const accounts = await ipcRenderer.invoke('get-provider-accounts', provider);
            updateProviderAccountsList(provider, accounts);
        }
    } catch (error) {
        console.error('加载账号列表失败:', error);
        showMessage('加载账号列表失败: ' + error.message, 'error');
    }
}

function updateProviderAccountsList(provider, accounts) {
    const providerNames = {
        tencent: '腾讯云 COS',
        aliyun: '阿里云 OSS',
        bytedance: '字节云 TOS',
        aws: 'AWS S3',
        huawei: '华为云 OBS'
    };
    
    const accountsList = document.getElementById(`${provider}Accounts`);
    if (!accountsList) return;
    
    accountsList.innerHTML = '';
    
    if (accounts && accounts.length > 0) {
        accounts.forEach(account => {
            const accountItem = document.createElement('div');
            accountItem.className = 'account-item';
            accountItem.innerHTML = `
                <div class="account-info">
                    <div class="account-name">${account.name}</div>
                    <div class="account-details">${account.isDefault ? '(默认)' : ''}</div>
                </div>
                <div class="account-actions">
                    <button class="btn btn-sm btn-secondary edit-account-btn" data-account-id="${account.id}" data-provider="${provider}">
                        <i class="fas fa-edit"></i> 编辑
                    </button>
                    <button class="btn btn-sm btn-danger delete-account-btn" data-account-id="${account.id}" data-provider="${provider}">
                        <i class="fas fa-trash"></i> 删除
                    </button>
                    ${!account.isDefault ? `<button class="btn btn-sm btn-primary set-default-btn" data-account-id="${account.id}" data-provider="${provider}"><i class="fas fa-star"></i> 设为默认</button>` : ''}
                </div>
            `;
            accountsList.appendChild(accountItem);
        });
        
        // 为动态创建的按钮添加事件监听器
        accountsList.querySelectorAll('.edit-account-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const accountId = e.target.closest('button').dataset.accountId;
                const provider = e.target.closest('button').dataset.provider;
                editAccount(accountId, provider);
            });
        });
        
        accountsList.querySelectorAll('.delete-account-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const accountId = e.target.closest('button').dataset.accountId;
                const provider = e.target.closest('button').dataset.provider;
                deleteAccount(accountId, provider);
            });
        });
        
        accountsList.querySelectorAll('.set-default-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const accountId = e.target.closest('button').dataset.accountId;
                const provider = e.target.closest('button').dataset.provider;
                setDefaultAccount(accountId, provider);
            });
        });
    } else {
        accountsList.innerHTML = '<div class="no-accounts">暂无配置的账号</div>';
    }
    
    // 添加新账号按钮
    const addButton = document.createElement('button');
    addButton.className = 'btn btn-primary add-account-btn';
    addButton.innerHTML = '<i class="fas fa-plus"></i> 添加账号';
    addButton.addEventListener('click', () => openAccountConfigModal(null, provider));
    accountsList.appendChild(addButton);
}

async function loadAccountForEdit(accountId, provider) {
    try {
        const account = await ipcRenderer.invoke('get-account-config', provider, accountId);
        if (account) {
            document.getElementById('accountName').value = account.accountName || '';
            document.getElementById('accountProvider').value = provider;
            document.getElementById('accountAccessKeyId').value = account.accessKeyId || '';
            document.getElementById('accountSecretAccessKey').value = account.secretAccessKey || '';
            document.getElementById('accountRegion').value = account.region || '';
            document.getElementById('accountBucket').value = account.bucket || '';
            document.getElementById('accountEndpoint').value = account.endpoint || '';
            document.getElementById('setAsDefault').checked = account.isDefault || false;
            
            // 设置编辑状态
            elements.accountConfigForm.dataset.accountId = accountId;
            
            // 更新模态框标题
            const titleElement = document.getElementById('accountConfigTitle');
            if (titleElement) {
                titleElement.textContent = '编辑账号';
            }
        }
    } catch (error) {
        console.error('加载账号配置失败:', error);
        showMessage('加载账号配置失败: ' + error.message, 'error');
    }
}

async function saveAccountConfig() {
    const accountName = document.getElementById('accountName').value.trim();
    const provider = document.getElementById('accountProvider').value;
    const accessKeyId = document.getElementById('accountAccessKeyId').value.trim();
    const secretAccessKey = document.getElementById('accountSecretAccessKey').value.trim();
    const region = document.getElementById('accountRegion').value.trim();
    const bucket = document.getElementById('accountBucket').value.trim();
    const endpoint = document.getElementById('accountEndpoint').value.trim();
    const isDefault = document.getElementById('setAsDefault').checked;
    const editAccountId = elements.accountConfigForm.dataset.accountId;
    
    // 验证必填字段
    if (!accountName || !provider || !accessKeyId || !secretAccessKey || !region || !bucket) {
        showMessage('请填写所有必填字段', 'error');
        return;
    }
    
    const config = {
        accessKeyId,
        secretAccessKey,
        region,
        bucket,
        endpoint
    };
    
    try {
        let success;
        if (editAccountId) {
            // 编辑现有账号
            success = await ipcRenderer.invoke('update-account-config', {
                provider,
                accountId: editAccountId,
                accountName,
                config
            });
        } else {
            // 新建账号
            const accountId = Date.now().toString(); // 生成唯一ID
            success = await ipcRenderer.invoke('save-account-config', {
                provider,
                accountId,
                accountName,
                config
            });
        }
        
        if (success) {
            // 如果设为默认账号，调用设置默认账号的API
            if (isDefault) {
                const accountId = editAccountId || Date.now().toString();
                await ipcRenderer.invoke('set-default-account', provider, accountId);
            }
            
            showMessage('账号配置保存成功', 'success');
            closeAccountConfigModal();
            loadAccountsForSettings();
            loadProviderConfigs();
            
            // 更新账号选择下拉菜单
            if (appState.selectedProvider === provider) {
                await loadAccountsForProvider(provider);
            }
        } else {
            showMessage('账号配置保存失败', 'error');
        }
    } catch (error) {
        console.error('保存账号配置失败:', error);
        showMessage('保存账号配置失败: ' + error.message, 'error');
    }
}

async function editAccount(accountId, provider) {
    openAccountConfigModal(accountId, provider);
}

async function deleteAccount(accountId, provider) {
    if (confirm('确定要删除这个账号配置吗？')) {
        try {
            const success = await ipcRenderer.invoke('delete-account', provider, accountId);
            if (success) {
                showMessage('账号删除成功', 'success');
                loadAccountsForSettings();
                loadProviderConfigs();
                
                // 更新账号选择下拉菜单
                if (appState.selectedProvider === provider) {
                    await loadAccountsForProvider(provider);
                }
            } else {
                showMessage('账号删除失败', 'error');
            }
        } catch (error) {
            console.error('删除账号失败:', error);
            showMessage('删除账号失败: ' + error.message, 'error');
        }
    }
}

async function setDefaultAccount(accountId, provider) {
    try {
        const success = await ipcRenderer.invoke('set-default-account', provider, accountId);
        if (success) {
            showMessage('默认账号设置成功', 'success');
            loadAccountsForSettings();
            
            // 更新账号选择下拉菜单
            if (appState.selectedProvider === provider) {
                await loadAccountsForProvider(provider);
            }
        } else {
            showMessage('设置默认账号失败', 'error');
        }
    } catch (error) {
        console.error('设置默认账号失败:', error);
        showMessage('设置默认账号失败: ' + error.message, 'error');
    }
}

async function loadAccountsForProvider(provider) {
    try {
        const accounts = await ipcRenderer.invoke('get-provider-accounts', provider);
        updateAccountSelect(accounts);
    } catch (error) {
        console.error('加载账号列表失败:', error);
    }
}

function updateAccountSelect(accounts) {
    if (!elements.accountSelect) return;
    
    // 清空现有选项
    elements.accountSelect.innerHTML = '<option value="">请选择账号或添加新账号</option>';
    
    if (accounts && accounts.length > 0) {
        accounts.forEach(account => {
            const option = document.createElement('option');
            option.value = account.id;
            option.textContent = account.name + (account.isDefault ? ' (默认)' : '');
            if (account.isDefault) {
                option.selected = true;
            }
            elements.accountSelect.appendChild(option);
        });
    }
}

async function onAccountSelectChange() {
    const selectedAccountId = elements.accountSelect.value;
    
    if (selectedAccountId && appState.selectedProvider) {
        try {
            const account = await ipcRenderer.invoke('get-account-config', appState.selectedProvider, selectedAccountId);
            if (account) {
                // 填充配置表单
                document.getElementById('accessKeyId').value = account.accessKeyId || '';
                document.getElementById('secretAccessKey').value = account.secretAccessKey || '';
                document.getElementById('region').value = account.region || '';
                document.getElementById('bucket').value = account.bucket || '';
                document.getElementById('endpoint').value = account.endpoint || '';
                
                // 检查连接状态
                checkConnectionStatus(appState.selectedProvider);
            }
        } catch (error) {
            console.error('加载账号配置失败:', error);
            showMessage('加载账号配置失败: ' + error.message, 'error');
        }
    } else {
        // 清空表单
        document.getElementById('accessKeyId').value = '';
        document.getElementById('secretAccessKey').value = '';
        document.getElementById('region').value = '';
        document.getElementById('bucket').value = '';
        document.getElementById('endpoint').value = '';
    }
}

// 测试账号连接
async function testAccountConnection() {
    const accountName = document.getElementById('accountName').value.trim();
    const provider = document.getElementById('accountProvider').value;
    const accessKeyId = document.getElementById('accountAccessKeyId').value.trim();
    const secretAccessKey = document.getElementById('accountSecretAccessKey').value.trim();
    const region = document.getElementById('accountRegion').value.trim();
    const bucket = document.getElementById('accountBucket').value.trim();
    const endpoint = document.getElementById('accountEndpoint').value.trim();
    
    if (!provider || !accessKeyId || !secretAccessKey || !region || !bucket) {
        showMessage('请填写所有必填字段后再测试连接', 'error');
        return;
    }
    
    const config = {
        provider,
        accessKeyId,
        secretAccessKey,
        region,
        bucket,
        endpoint
    };
    
    const testBtn = document.getElementById('testAccountConnectionBtn');
    const originalText = testBtn.innerHTML;
    testBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 测试中...';
    testBtn.disabled = true;
    
    try {
        const result = await ipcRenderer.invoke('test-cloud-connection', config);
        if (result.success) {
            showMessage('连接测试成功！', 'success');
        } else {
            showMessage('连接测试失败: ' + result.error, 'error');
        }
    } catch (error) {
        console.error('测试连接失败:', error);
        showMessage('测试连接失败: ' + error.message, 'error');
    } finally {
        testBtn.innerHTML = originalText;
        testBtn.disabled = false;
    }
}

// 切换设置标签页
function switchTab(tabName) {
    // 移除所有标签页的激活状态
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    
    // 隐藏所有标签页内容
    document.querySelectorAll('.tab-content').forEach(content => {
        content.style.display = 'none';
    });
    
    // 激活选中的标签页
    const activeBtn = document.querySelector(`[data-tab="${tabName}"]`);
    if (activeBtn) {
        activeBtn.classList.add('active');
    }
    
    // 显示对应的标签页内容
    const activeContent = document.getElementById(`${tabName}Tab`);
    if (activeContent) {
        activeContent.style.display = 'block';
    }
}

// 主界面云服务提供商选择变化
async function onProviderSelectChange() {
    const selectedProvider = elements.providerSelect.value;
    
    if (selectedProvider) {
        appState.selectedProvider = selectedProvider;
        
        // 显示账号选择组
        elements.accountSelectGroup.style.display = 'block';
        
        // 加载该提供商的账号列表
        try {
            const accounts = await ipcRenderer.invoke('get-provider-accounts', selectedProvider);
            updateMainAccountSelect(accounts);
            
            // 如果有默认账号，自动选择
            const defaultAccount = accounts.find(account => account.isDefault);
            if (defaultAccount) {
                elements.mainAccountSelect.value = defaultAccount.id;
                await onMainAccountSelectChange();
            }
        } catch (error) {
            console.error('加载账号列表失败:', error);
            showMessage('加载账号列表失败: ' + error.message, 'error');
        }
    } else {
        appState.selectedProvider = null;
        elements.accountSelectGroup.style.display = 'none';
        elements.connectionStatus.style.display = 'none';
        updateUI();
    }
}

// 主界面账号选择变化
async function onMainAccountSelectChange() {
    const selectedAccountId = elements.mainAccountSelect.value;
    
    if (selectedAccountId && appState.selectedProvider) {
        try {
            const account = await ipcRenderer.invoke('get-account-config', appState.selectedProvider, selectedAccountId);
            if (account) {
                // 显示连接状态
                elements.connectionStatus.style.display = 'block';
                
                // 检查连接状态
                await checkMainConnectionStatus(appState.selectedProvider, account);
                
                // 更新UI状态
                updateUI();
            }
        } catch (error) {
            console.error('加载账号配置失败:', error);
            showMessage('加载账号配置失败: ' + error.message, 'error');
        }
    } else {
        elements.connectionStatus.style.display = 'none';
        appState.isConnected = false;
        updateUI();
    }
}

// 更新主界面账号选择器
function updateMainAccountSelect(accounts) {
    elements.mainAccountSelect.innerHTML = '<option value="">请选择账号</option>';
    
    accounts.forEach(account => {
        const option = document.createElement('option');
        option.value = account.id;
        option.textContent = account.name;
        if (account.isDefault) {
            option.textContent += ' (默认)';
        }
        elements.mainAccountSelect.appendChild(option);
    });
}

// 检查主界面连接状态
async function checkMainConnectionStatus(provider, account) {
    if (appState.connectionChecking) return;
    
    appState.connectionChecking = true;
    elements.statusText.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 检查中...';
    
    try {
        const config = {
            provider: provider,
            accessKeyId: account.accessKeyId,
            secretAccessKey: account.secretAccessKey,
            region: account.region,
            bucket: account.bucket,
            endpoint: account.endpoint
        };
        
        const result = await ipcRenderer.invoke('test-cloud-connection', config);
        
        if (result.success) {
            appState.isConnected = true;
            elements.statusText.innerHTML = '<i class="fas fa-check-circle" style="color: #28a745;"></i> 已连接';
        } else {
            appState.isConnected = false;
            elements.statusText.innerHTML = '<i class="fas fa-times-circle" style="color: #dc3545;"></i> 连接失败';
        }
    } catch (error) {
        appState.isConnected = false;
        elements.statusText.innerHTML = '<i class="fas fa-times-circle" style="color: #dc3545;"></i> 连接错误';
        console.error('连接测试失败:', error);
    } finally {
        appState.connectionChecking = false;
    }
}

// 初始化主界面云服务选择器
async function initializeMainCloudSelector() {
    try {
        // 加载所有提供商的账号，检查是否有配置
        const providers = ['tencent', 'aliyun', 'bytedance', 'aws', 'huawei'];
        let hasAnyAccount = false;
        
        for (const provider of providers) {
            const accounts = await ipcRenderer.invoke('get-provider-accounts', provider);
            if (accounts && accounts.length > 0) {
                hasAnyAccount = true;
                break;
            }
        }
        
        if (hasAnyAccount) {
            // 如果有账号配置，尝试加载上次选择的提供商
            // 这里可以添加记住上次选择的逻辑
        }
    } catch (error) {
        console.error('初始化云服务选择器失败:', error);
    }
}

// 设置菜单事件监听器
function setupMenuEventListeners() {
    // 监听来自主进程的菜单事件
    ipcRenderer.on('menu-select-local-directory', () => {
        selectLocalDirectory();
    });
    
    ipcRenderer.on('menu-open-settings', () => {
        openSettingsModal();
    });
    
    ipcRenderer.on('menu-compare-files', () => {
        if (!elements.compareBtn.disabled) {
            compareFiles();
        }
    });
    
    ipcRenderer.on('menu-start-upload', () => {
        if (!elements.uploadBtn.disabled) {
            startUpload();
        }
    });
    
    ipcRenderer.on('menu-stop-upload', () => {
        if (appState.isUploading) {
            // 这里可以添加停止上传的逻辑
            showMessage('停止上传功能待实现', 'info');
        }
    });
    
    ipcRenderer.on('menu-show-about', () => {
        showAboutDialog();
    });
}

// 显示关于对话框
function showAboutDialog() {
    const aboutMessage = `
        <div style="text-align: center; padding: 20px;">
            <h3>资源桶上传工具</h3>
            <p>版本: 1.0.0</p>
            <p>一个用于上传资源到各种云存储服务的工具</p>
            <p>支持腾讯云COS、阿里云OSS、AWS S3、华为云OBS、字节跳动火山引擎</p>
            <br>
            <p>© 2024 资源桶上传工具</p>
        </div>
    `;
    showMessage(aboutMessage, 'info');
}

document.addEventListener('DOMContentLoaded', initializeApp);